<?php

/**
 * @author Silk
 */
class Silk_Mapi_Model_Sms
{

    const DEBUG = TRUE;

    // Green land SMS system api base url.
    const API_SMS_WEB_SERVICE_URI = "http://api.cnsms.cn/";
    //const API_SMS_WEB_USERNAME = '107627';
    //const API_SMS_WEB_PASSWORD = 'silksoftware';
    const API_SMS_WEB_USERNAME = '113095';
    const API_SMS_WEB_PASSWORD = '123456hhh';


    // Zend http client class
    protected $_http_client;

    // verification code length by default
    public $verification_code_length = 6;

    protected function _http()
    {

        if (!$this->_http_client) {

            require_once "Zend/Http/Client.php";

            $this->_http_client = new Zend_Http_Client;
        }

        return $this->_http_client;

    }

    /**
     * Send mobile phone verification code
     *
     * @param $mobile number The mobile phone number
     * @param $code string The verification code
     *
     * @return verification code | FALSE
     *
     */
    public function sendCode($mobile, $code = NULL)
    {

        if (NULL === $code) {
            $code = Mage::helper('core')->getRandomString(
                $this->verification_code_length,
                Mage_Core_Helper_Data::CHARS_PASSWORD_DIGITS
            );
        }

        // @TODO Add the template
        $code_template = "您好，您的轻松老板注册验证码是{$code}。";

        if ($this->sendText($mobile, $code_template)) {
            return $code;
        }
        return false;

    }

    public function sendNewOrder($mobile, $orderId)
    {
        // @TODO Add the template
        $template = "您好，您的订单已收到（$orderId）,我们将尽快安排送货。";

        if ($this->sendText($mobile, $template)) {
            return true;
        }
        return false;
    }

    /**
     * Send mobile phone text
     *
     * @param $mobile number The mobile phone number
     * @param $text string The text content
     *
     * @return TRUE|FALSE
     */
    public function sendText($mobile, $text)
    {

        $default = array(
            'uid' => self::API_SMS_WEB_USERNAME,
            'pwd' => md5(self::API_SMS_WEB_PASSWORD),
            'mobile' => $mobile,
            'content' => urlencode($text),
            'ac' => 'send'  // 具体操作
        );

        // send logic here... @XXX
        $response = $this->_http()
            ->setUri(self::API_SMS_WEB_SERVICE_URI)
            ->setParameterPost($default)
            ->request(Zend_Http_Client::POST);
        return (200 == $response->getStatus()) && ('100' == $response->getBody());
    }


}
